#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
#include<assert.h>


#define NUM 1024
char linecommand[NUM];
char* argv_[60];
int lastcode =0;
int lastsig = 0;



int main()
{
    while(1)
    {
//打印提示符
        printf("用户名@主机名 当前路劲#");
        fflush(stdout);
//获取用户输入
        char* str = fgets(linecommand, NUM-1, stdin);
        assert(str != NULL);
        (void)str;
        //清楚最后一个\n的字符，
        //因为我们输入完成后会敲入一个回车键，回车也会被获取到linecommand中
        linecommand[strlen(linecommand)-1] = '\0';//消除最后的回车键
        //printf("%s\n",linecommand);//获取成功
        
//分割linecommand，
        argv_[0] = strtok(linecommand," "); 
        int i = 1;
        //处理ls的颜色和缩写
        if(strcmp(argv_[0],"ll") == 0){argv_[0] = (char*)"ls";argv_[i++] = (char*)"-l";}
        if(strcmp(argv_[0],"ls") == 0){argv_[i++] = (char*)"--color=auto";}
        while((argv_[i++] = strtok(NULL, " "))!=NULL);
        
        //处理cd 和 echo这样的内建命令
        if(argv_[0] != NULL && strcmp(argv_[0], "cd")== 0){
            if(argv_[1] != NULL)chdir(argv_[1]);
            continue;
        }
        if(argv_[0] != NULL && argv_[1] != NULL && strcmp(argv_[0], "echo")==0 && getenv(((char*)argv_[1])+1) == NULL){
            if(strcmp(argv_[1], "$?")==0)
                printf("code:%d sig:%d\n", lastcode,lastsig);
            else
                printf("%s\n",argv_[1]);
            continue;
        }

//创建子进程，进行程序替换
        pid_t id = fork();
        assert(id != -1);
        if(id == 0 )
        {
            execvp(argv_[0], argv_);
            exit(1);
        }

        int status = 0;
        pid_t ret = waitpid(id, &status, 0);//阻塞等待
        assert(ret > 0);
        (void)ret ;
        lastcode = ((status>>8)&0xff);
        lastsig = (status&0x7f);

    }
}
